package com.xueyi.tesla.mapper;

import com.xueyi.core.entity.po.GameBackendUserLoginLog;
import com.xueyi.game.backend.entity.dto.SaveBaseUserDto;
import com.xueyi.game.backend.entity.dto.UserTableDto;
import com.xueyi.game.backend.entity.po.BaseLog;
import com.xueyi.game.backend.entity.po.BaseMenu;
import com.xueyi.game.backend.entity.po.BaseUser;
import com.xueyi.game.backend.entity.vo.UserTableVo;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 描述 用户的基础Mapper
 *
 * @auther 俞烨
 * @date 2022-11-08 15
 */
public interface BackendBaseAccountMapper extends BaseMapper {

    @Select("SELECT * FROM ${table} WHERE account = #{account} AND password = #{password}")
    BaseUser userLogin(@Param("account") String account,
                       @Param("password") String password,
                       @Param("table") String table);

    @Select("SELECT distinct role_id FROM  ${table} WHERE user_id = #{id}")
    List<Integer> findUserRoleList(@Param("id") Integer id,
                                   @Param("table") String table);

    @Insert("INSERT INTO ${table} (account , password , u_phone , u_photo , u_name) VALUES (" +
            "#{req.account} , #{req.password} , #{req.uPhone} , #{req.uPhoto} , #{req.uName}" +
            ")")
    @Options(useGeneratedKeys = true, keyProperty = "req.id")
    void save(@Param("req") SaveBaseUserDto saveBaseUser,
              @Param("table") String table);

    @Insert("<script>" +
            " INSERT INTO ${table} (user_id , role_id) VALUES " +
            " <foreach collection='roleIds' item='item' separator=','> " +
            " (#{id} , #{item}) " +
            " </foreach> " +
            "</script>")
    void batchSaveRole(@Param("roleIds") String[] roleSplit,
                       @Param("id") Integer id,
                       @Param("table") String table);

    @Select("SELECT * FROM ${table} WHERE id = #{id} AND is_valid = 1")
    SaveBaseUserDto findUserById(@Param("id") Integer userId,
                                 @Param("table") String userTableName);

    /**
     * 修改用户的信息
     *
     * @param saveBaseUser
     */
    @Update("<script>" +
            " UPDATE ${table} SET account = #{req.account} , u_phone = #{req.uPhone}  ," +
            " u_photo = #{req.uPhoto} , u_name = #{req.uName}" +
            " <if test = ' req.password!= null ' >" +
            "  , password = #{req.password} " +
            " </if> " +
            " WHERE id = #{req.id} " +

            "</script>")
    int edit(@Param("req") SaveBaseUserDto saveBaseUser,
              @Param("table") String userTableName);

    @Delete("DELETE FROM ${table} WHERE user_id = #{id}")
    void delUserRole(@Param("id") Integer userId,
                     @Param("table") String userTableName);

    @Update("UPDATE ${table} SET is_valid = #{status} WHERE id = #{id}")
    void delOrRecover(@Param("id") Integer userId,
                      @Param("status") Integer currentStatus,
                      @Param("table") String userTableName);

    @Select("<script>" +
            " SELECT COUNT(id) FROM ${table} " +
            " <where> " +
            " <if test='req.isValid != null'>" +
            "   AND is_valid = #{req.isValid}" +
            " </if> " +
            " <if test='req.keyWord != null'>" +
            "   AND (account = #{req.keyWord} OR u_phone LIKE '%${req.keyWord}%')" +
            " </if> " +
            " <if test='req.roleId != null'>" +
            "   AND id IN ( SELECT user_id FROM ${roleTable} WHERE role_id = #{req.roleId})" +
            " </if> " +
            " </where> " +
            "</script>")
    Integer findUserListTotal(@Param("req") UserTableDto userTableReq,
                              @Param("table") String userTableName,
                              @Param("roleTable") String roleTable);

    @Select("<script>" +
            " SELECT a1.* , GROUP_CONCAT(role.role_name) roleName FROM ( " +
            " SELECT * FROM ${table} " +
            " <where> " +
            " <if test='req.isValid != null'>" +
            "   AND is_valid = #{req.isValid}" +
            " </if> " +
            " <if test='req.keyWord != null'>" +
            "   AND (account = #{req.keyWord} OR u_phone LIKE '%${req.keyWord}%')" +
            " </if> " +
            " <if test='req.roleId != null'>" +
            "   AND id IN ( SELECT user_id FROM ${userJoinRoleTable} WHERE role_id = #{req.roleId})" +
            " </if> " +
            " </where> " +
            " ORDER BY create_time DESC LIMIT #{req.startIndex} , #{req.limit}" +
            " ) a1 LEFT JOIN ${userJoinRoleTable} userJoinRoleTable ON a1.id = userJoinRoleTable.user_id " +
            " LEFT JOIN  ${roleTable} role ON  userJoinRoleTable.role_id = role.id" +
            "  GROUP BY a1.id " +
            "</script>")
    List<UserTableVo> findUserList(@Param("req") UserTableDto userTableReq,
                                   @Param("table") String userTableName,
                                   @Param("userJoinRoleTable") String userJoinRoleTable,
                                   @Param("roleTable") String roleTable);


    /**
     * 查询该用户的所有菜单信息
     *
     * @param id
     * @return
     */
    @Select("SELECT * FROM ${menuTableName} WHERE is_valid = 1 AND authority_type = 1 AND id IN (" +
            " SELECT menu_id FROM ${roleJoinAuthTableName} WHERE role_id IN ( " +
            "   SELECT role_id FROM ${userJoinRoleTableName} WHERE user_id = #{id} AND is_valid = 1 " +
            " )" +
            " ) ORDER BY create_time ASC ")
    List<BaseMenu> findUserLeftMenuList(@Param("id") Integer id, @Param("menuTableName") String menuTableName,
                                        @Param("roleJoinAuthTableName") String roleJoinAuthTableName,
                                        @Param("userJoinRoleTableName") String userJoinRoleTableName);


    /**
     * 获取用户操作日志总条数
     *
     * @param userId    用户id
     * @param startTime 起始时间
     * @param endTime   结束时间
     * @param table     表名
     * @return
     * @author hxs
     */
    @Select({
            " <script>" +
                    " select count(id) from ${table} where user_id = #{userId} " +
                    " <if test=' startTime!=null and endTime!=null ' >" +
                    " and create_time between #{startTime} and #{endTime} " +
                    " </if> " +
                    " </script> "
    })
    Integer findUserLogByUserIdTotal(@Param("userId") Integer userId, String startTime, String endTime, String table);


    /**
     * 获取用户操作日志列表
     *
     * @param userId           用户id
     * @param startTime        起始时间
     * @param endTime          结束时间
     * @param startIndex       起始位置
     * @param limit            每页条数
     * @param userLogTableName 表名
     * @return
     * @author hxs
     */
    @Select({
            " <script>" +
                    " select * from ${table} where user_id = #{userId} " +
                    " <if test = ' startTime != null and endTime != null '>" +
                    " and create_time between #{startTime} and #{endTime} " +
                    " </if> " +
                    " order by create_time desc limit #{startIndex} , #{limit} " +
                    "</script> "
    })
    List<BaseLog> findUserLogByUserId(@Param("userId") Integer userId, @Param("startTime") String startTime, @Param("endTime") String endTime,
                                      @Param("startIndex") Integer startIndex, @Param("limit") Integer limit, @Param("table") String userLogTableName);

    @Insert({
            " insert into game_backend_user_login_log ( backend_user_id , backend_username , ip_address ) " +
                    " values (   #{item.backendUserId} , #{item.backendUsername} , #{item.ipAddress} ) "
    })
    void saveUserLoginLog(@Param("item") GameBackendUserLoginLog log);
}
